#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
高德地图命令处理器
处理地图相关的语音命令
"""

from typing import Dict, Any, Optional

try:
    from .amap_rest_service import AmapRestService
    from config.amap_config import AmapConfig
    from config.user_config import UserConfig
except ImportError:
    import sys
    import os
    sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
    from services.amap_rest_service import AmapRestService
    from config.amap_config import AmapConfig
    from config.user_config import UserConfig


class AmapCommandHandler:
    """高德地图命令处理器"""
    
    def __init__(self):
        """初始化地图命令处理器"""
        self.amap_service = None
        self.enabled = False
        
        # 尝试初始化高德地图服务
        if AmapConfig.AMAP_ENABLED and AmapConfig.validate():
            try:
                self.amap_service = AmapRestService(AmapConfig.AMAP_API_KEY)
                self.enabled = True
                print("✅ 地图命令处理器已启用")
            except Exception as e:
                print(f"⚠️  地图服务初始化失败: {str(e)}")
                self.enabled = False
        else:
            print("ℹ️  地图服务未配置")
    
    def handle(self, action: str, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """
        处理地图命令
        
        Args:
            action: 动作类型（weather/search/route/geocode/nearby）
            parameters: 命令参数
            
        Returns:
            执行结果
        """
        if not self.enabled:
            return {
                "success": False,
                "message": "地图服务未启用",
                "data": None
            }
        
        try:
            # 根据action分发到具体的处理方法
            if action == "weather":
                return self._handle_weather(parameters)
            elif action == "search":
                return self._handle_search(parameters)
            elif action == "route":
                return self._handle_route(parameters)
            elif action == "geocode":
                return self._handle_geocode(parameters)
            elif action == "nearby":
                return self._handle_nearby(parameters)
            else:
                return {
                    "success": False,
                    "message": f"不支持的地图操作: {action}",
                    "data": None
                }
        except Exception as e:
            return {
                "success": False,
                "message": f"地图命令执行失败: {str(e)}",
                "data": None
            }
    
    def _parse_time(self, time_str: str) -> int:
        """
        解析时间字符串，返回相对今天的天数偏移
        
        Args:
            time_str: 时间字符串（今天、明天、后天等）
            
        Returns:
            天数偏移（0=今天，1=明天，2=后天，以此类推）
        """
        time_map = {
            "今天": 0, "今日": 0,
            "明天": 1, "明日": 1,
            "后天": 2,
            "大后天": 3,
            "昨天": -1, "昨日": -1,
            "前天": -2
        }
        return time_map.get(time_str, 0)
    
    def _handle_weather(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """处理天气查询"""
        city = parameters.get("city")
        time_str = parameters.get("time", "今天")
        
        # 如果没有指定城市，使用用户默认城市
        if not city or city in ["当前城市", "这里", "当前", "本地"]:
            city = UserConfig.get_default_city()
            print(f"📍 使用默认城市: {city}")
        
        # 解析时间
        day_offset = self._parse_time(time_str)
        print(f"📅 时间: {time_str} (偏移: {day_offset}天)")
        
        # 如果查询今天的天气，使用实时天气API
        if day_offset == 0:
            result = self.amap_service.get_weather(city, extensions='base')
            
            if result['success']:
                weather_data = result['data'].get('lives', [{}])[0]
                weather = weather_data.get('weather', '未知')
                temperature = weather_data.get('temperature', '未知')
                wind = weather_data.get('winddirection', '')
                windpower = weather_data.get('windpower', '')
                humidity = weather_data.get('humidity', '')
                
                # 构建语音回复
                voice_reply = f"{city}今天{weather}，温度{temperature}度"
                if wind and windpower:
                    voice_reply += f"，{wind}风{windpower}级"
                if humidity:
                    voice_reply += f"，湿度{humidity}%"
                
                return {
                    "success": True,
                    "message": f"查询到{city}的天气",
                    "data": {
                        "city": city,
                        "time": "今天",
                        "weather": weather,
                        "temperature": temperature,
                        "wind": f"{wind}{windpower}",
                        "humidity": f"{humidity}%",
                        "full_data": weather_data
                    },
                    "voice_reply": voice_reply
                }
        
        # 查询未来天气，使用天气预报API
        elif day_offset > 0 and day_offset <= 3:
            result = self.amap_service.get_weather(city, extensions='all')
            
            if result['success']:
                forecasts = result['data'].get('forecasts', [])
                if not forecasts:
                    return {
                        "success": False,
                        "message": "未获取到天气预报数据",
                        "data": None,
                        "voice_reply": f"抱歉，暂时无法获取{city}{time_str}的天气预报"
                    }
                
                # 获取预报列表
                casts = forecasts[0].get('casts', [])
                
                # 获取对应日期的天气（day_offset对应数组索引）
                if day_offset < len(casts):
                    weather_data = casts[day_offset]
                    date = weather_data.get('date', '')
                    week = weather_data.get('week', '')
                    weather_day = weather_data.get('dayweather', '未知')
                    weather_night = weather_data.get('nightweather', '未知')
                    temp_day = weather_data.get('daytemp', '未知')
                    temp_night = weather_data.get('nighttemp', '未知')
                    wind_day = weather_data.get('daywind', '')
                    windpower_day = weather_data.get('daypower', '')
                    
                    # 构建语音回复
                    if weather_day == weather_night:
                        weather_desc = weather_day
                    else:
                        weather_desc = f"{weather_day}转{weather_night}"
                    
                    voice_reply = f"{city}{time_str}{weather_desc}，气温{temp_night}到{temp_day}度"
                    if wind_day and windpower_day:
                        voice_reply += f"，{wind_day}风{windpower_day}级"
                    
                    return {
                        "success": True,
                        "message": f"查询到{city}{time_str}的天气",
                        "data": {
                            "city": city,
                            "time": time_str,
                            "date": date,
                            "week": week,
                            "weather": weather_desc,
                            "temp_high": temp_day,
                            "temp_low": temp_night,
                            "wind": f"{wind_day}{windpower_day}",
                            "full_data": weather_data
                        },
                        "voice_reply": voice_reply
                    }
                else:
                    return {
                        "success": False,
                        "message": "天气预报数据不足",
                        "data": None,
                        "voice_reply": f"抱歉，暂时无法获取{city}{time_str}的天气预报"
                    }
        
        # 不支持的时间范围
        else:
            if day_offset < 0:
                return {
                    "success": False,
                    "message": "不支持查询过去的天气",
                    "data": None,
                    "voice_reply": f"抱歉，暂不支持查询{time_str}的天气"
                }
            else:
                return {
                    "success": False,
                    "message": "天气预报最多支持未来3天",
                    "data": None,
                    "voice_reply": f"抱歉，天气预报最多只能查询到后天"
                }
        
        # 查询失败
        return {
            "success": False,
            "message": result.get('error', '天气查询失败'),
            "data": None,
            "voice_reply": f"抱歉，无法查询{city}的天气信息"
        }
    
    def _handle_search(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """处理地点搜索"""
        keywords = parameters.get("keywords")
        city = parameters.get("city")
        
        if not keywords:
            return {
                "success": False,
                "message": "请指定要搜索的关键词",
                "data": None,
                "voice_reply": "请告诉我您要搜索什么"
            }
        
        result = self.amap_service.search_poi(keywords, city)
        
        if result['success']:
            pois = result['data'].get('pois', [])
            count = len(pois)
            
            if count == 0:
                voice_reply = f"没有找到{keywords}"
                if city:
                    voice_reply += f"在{city}"
            else:
                # 获取前3个结果
                top_results = pois[:3]
                locations = []
                for poi in top_results:
                    name = poi.get('name', '')
                    address = poi.get('address', '')
                    locations.append({"name": name, "address": address})
                
                voice_reply = f"找到{count}个{keywords}"
                if city:
                    voice_reply += f"在{city}"
                voice_reply += f"，最近的是{top_results[0].get('name', '')}"
                if top_results[0].get('address'):
                    voice_reply += f"，地址是{top_results[0].get('address')}"
            
            return {
                "success": True,
                "message": f"找到{count}个结果",
                "data": {
                    "count": count,
                    "results": pois[:5],  # 返回前5个结果
                    "keywords": keywords,
                    "city": city
                },
                "voice_reply": voice_reply
            }
        else:
            return {
                "success": False,
                "message": result.get('error', '搜索失败'),
                "data": None,
                "voice_reply": f"抱歉，搜索{keywords}时出错了"
            }
    
    def _handle_route(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """处理路线规划"""
        origin = parameters.get("origin", "当前位置")
        destination = parameters.get("destination")
        mode = parameters.get("mode", "driving")
        city = parameters.get("city")
        
        if not destination:
            return {
                "success": False,
                "message": "请指定目的地",
                "data": None,
                "voice_reply": "请告诉我您要去哪里"
            }
        
        # 如果没有起点，提示用户
        if origin == "当前位置":
            return {
                "success": False,
                "message": "请指定出发地",
                "data": None,
                "voice_reply": f"请告诉我您从哪里出发去{destination}"
            }
        
        result = self.amap_service.plan_route(origin, destination, mode, city)
        
        if result['success']:
            route = result['data'].get('route', {})
            paths = route.get('paths', [])
            
            if paths:
                path = paths[0]
                distance = int(path.get('distance', 0)) / 1000  # 转换为公里
                duration = int(path.get('duration', 0)) / 60  # 转换为分钟
                
                # 根据出行方式描述
                mode_text = {
                    "driving": "驾车",
                    "walking": "步行",
                    "transit": "乘坐公交",
                    "riding": "骑行"
                }.get(mode, mode)
                
                voice_reply = f"从{origin}到{destination}，{mode_text}距离{distance:.1f}公里，大约需要{duration:.0f}分钟"
                
                return {
                    "success": True,
                    "message": "路线规划成功",
                    "data": {
                        "origin": origin,
                        "destination": destination,
                        "mode": mode,
                        "distance_km": round(distance, 1),
                        "duration_minutes": round(duration, 0),
                        "path": path
                    },
                    "voice_reply": voice_reply
                }
            else:
                return {
                    "success": False,
                    "message": "未找到可用路线",
                    "data": None,
                    "voice_reply": f"抱歉，无法规划从{origin}到{destination}的路线"
                }
        else:
            return {
                "success": False,
                "message": result.get('error', '路线规划失败'),
                "data": None,
                "voice_reply": f"抱歉，无法规划到{destination}的路线"
            }
    
    def _handle_geocode(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """处理地理编码（地址查询）"""
        address = parameters.get("address")
        city = parameters.get("city")
        
        if not address:
            return {
                "success": False,
                "message": "请指定要查询的地址",
                "data": None,
                "voice_reply": "请告诉我您要查询哪个地点的地址"
            }
        
        result = self.amap_service.geocode(address, city)
        
        if result['success']:
            geocodes = result['data'].get('geocodes', [])
            if geocodes:
                geocode = geocodes[0]
                formatted_address = geocode.get('formatted_address', '')
                location = geocode.get('location', '')
                
                voice_reply = f"{address}的地址是{formatted_address}"
                
                return {
                    "success": True,
                    "message": "地址查询成功",
                    "data": {
                        "address": address,
                        "formatted_address": formatted_address,
                        "location": location,
                        "geocode": geocode
                    },
                    "voice_reply": voice_reply
                }
            else:
                return {
                    "success": False,
                    "message": "未找到该地址",
                    "data": None,
                    "voice_reply": f"抱歉，没有找到{address}的地址信息"
                }
        else:
            return {
                "success": False,
                "message": result.get('error', '地址查询失败'),
                "data": None,
                "voice_reply": f"抱歉，无法查询{address}的地址"
            }
    
    def _handle_nearby(self, parameters: Dict[str, Any]) -> Dict[str, Any]:
        """处理周边搜索"""
        keywords = parameters.get("keywords")
        location = parameters.get("location")
        
        if not keywords:
            return {
                "success": False,
                "message": "请指定要搜索的关键词",
                "data": None,
                "voice_reply": "请告诉我您要搜索什么"
            }
        
        if not location:
            return {
                "success": False,
                "message": "需要位置信息才能搜索周边",
                "data": None,
                "voice_reply": "需要知道您的位置才能搜索周边"
            }
        
        result = self.amap_service.search_around(location, keywords)
        
        if result['success']:
            pois = result['data'].get('pois', [])
            count = len(pois)
            
            voice_reply = f"在您周边找到{count}个{keywords}"
            if pois:
                voice_reply += f"，最近的是{pois[0].get('name', '')}"
            
            return {
                "success": True,
                "message": f"找到{count}个周边结果",
                "data": {
                    "count": count,
                    "results": pois[:5],
                    "keywords": keywords
                },
                "voice_reply": voice_reply
            }
        else:
            return {
                "success": False,
                "message": result.get('error', '周边搜索失败'),
                "data": None,
                "voice_reply": f"抱歉，搜索周边{keywords}时出错了"
            }
    
    def is_enabled(self) -> bool:
        """检查服务是否启用"""
        return self.enabled


def main():
    """测试函数"""
    handler = AmapCommandHandler()
    
    if not handler.is_enabled():
        print("❌ 地图服务未启用，请先配置API Key")
        return
    
    print("🧪 测试地图命令处理器...")
    print("=" * 60)
    
    # 测试1: 天气查询
    print("\n【测试1: 天气查询】")
    result = handler.handle("weather", {"city": "北京"})
    print(f"结果: {result['voice_reply']}")
    
    # 测试2: 地点搜索
    print("\n【测试2: 地点搜索】")
    result = handler.handle("search", {"keywords": "咖啡馆", "city": "上海"})
    print(f"结果: {result['voice_reply']}")
    
    # 测试3: 路线规划
    print("\n【测试3: 路线规划】")
    result = handler.handle("route", {
        "origin": "天安门",
        "destination": "鸟巢",
        "mode": "driving",
        "city": "北京"
    })
    print(f"结果: {result['voice_reply']}")
    
    print("\n" + "=" * 60)
    print("✅ 测试完成")


if __name__ == "__main__":
    main()

